<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="renderer" content="webkit">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="/favicon.ico">
  <title>智慧播控监管平台</title>
  <style>
    html,
    body,
    #app{
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #no_program {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2rem;
        width: 100%;
        height: 100%;
        min-height: 0;
    }
  </style>
      <script type="text/javascript">
          var requestUrl = 'http://10.104.104.179:9086'

          function resetFontSize(width, height){
              var baseWidth = width || 1920
              var baseHeight = height || 1080
              var baseFontSize = 100
              var clientWidth = document.body.clientWidth
              var fontSize = Math.min((clientWidth / baseWidth) * baseFontSize, 100) + 'px'
              document.querySelector('html').style.fontSize = fontSize
          }

          function request(url, method, data, callback) {
              // 创建一个新的 XMLHttpRequest 对象
              var xhr = new XMLHttpRequest();
              // 设置请求类型和方法
              xhr.open(method, url, true);
              // 监听请求状态变化
              xhr.onreadystatechange = function() {
                  if (xhr.readyState === 4 && xhr.status === 200) {
                      // 请求成功，调用回调函数并传入响应数据
                      callback(null, JSON.parse(xhr.responseText));
                  } else if (xhr.readyState === 4) {
                      // 请求失败，调用回调函数并传入错误信息
                      callback(xhr.statusText, null);
                  }
              };
              // 设置请求头（如果需要）
              xhr.setRequestHeader('Content-Type', 'application/json');
              // 发送 GET 请求
              xhr.send();
          }

          // 更新时间
          function setCurrentTime (serverTime) {
              console.log('set current time:' + serverTime)
              if (serverTimeInterval) {
                  clearInterval(serverTimeInterval)
                  serverTimeInterval = null;
              }
              try {
                  currentTime = +serverTime
              }catch (e){
                  currentTime = new Date().getTime()
              }
              console.log('current time:::', currentTime)
              getCurrentTime()
          }

          var getQueryParams = function(url) {
              var splitCharIndex = url.indexOf('?');
              var params = {};
              if (splitCharIndex > 0) {
                  var paramsStrArr = url.substring(splitCharIndex + 1).split('&');
                  paramsStrArr.forEach(paramsStr => {
                      var paramName = paramsStr.split('=')[0];
                      params[paramName] = paramsStr.split('=')[1];
                  });
              }
              return params;
          }

          function isVideo (url) {
             var videoSuffix = "mp3,wav,mp4,flv,avi,mov,rm,webm,ts,rm,mkv,mpeg,ogg,mpg,rmvb,wmv,3gp,ts,swf".split(",")
              if (!url) return false
              const suffix = url.substring(url.lastIndexOf(".") + 1)
              return videoSuffix.includes(suffix.toLowerCase())
          }

          function isHtml (url) {
              var suffixs = "html, htm".split(",")
              if (!url) return false
              const suffix = url.substring(url.lastIndexOf(".") + 1)
              return suffixs.includes(suffix.toLowerCase())
          }

          function setVideoDisplay() {
              videoLoading = false
              document.getElementById("video").src = dataList[playIndex].url
              document.getElementById("video").style.display = ''
              document.getElementById("image").style.display = 'none'
              document.getElementById("video").onloadeddata = onVideoLoaded
              document.getElementById("video").ontimeupdate = onVideoPlaying
              videoAwaitInterval = setInterval(function () {
                  videoAwaitCurrent += 1
                  if (videoAwaitCurrent >= videoAwaitSecond && !videoLoading) {
                      play()
                  }
              }, 1000)

          }
          function onVideoLoaded() {
              const video = document.getElementById("video")
              videoDuration = video.duration
          }
          function onVideoPlaying() {
              if (videoAwaitInterval) {
                  clearInterval(videoAwaitInterval)
                  videoAwaitInterval = null
              }
              const video = document.getElementById("video")
              videoLoading = true
              if (video.currentTime >= video.duration) {
                  play()
              }
          }
          function setImageDisplay() {
              document.getElementById("image").src = dataList[playIndex].url
              document.getElementById("image").style.display = ''
              document.getElementById("video").style.display = 'none'
          }

          function showNoProgram() {
              document.getElementById("no_program").style.display = ''
              if (playLoading) {
                  document.getElementById("no_program").innerText = "节目加载中..."
              } else {
                  document.getElementById("no_program").innerText = "暂无节目"
              }
          }

          var playTimeout = null, playIndex = -1,
              // 当前界面清单
              dataList = [],
              // 当前界面配置
              config = {},
              // 当前播放视频时长
              videoDuration = 0,
              videoLoading = false,
              videoAwaitSecond = 60,
              videoAwaitInterval = null,
              videoAwaitCurrent = 0,
              // 定时播放校验器
              playTimeInterval = null,
              // 时间计算器
              serverTimeInterval = null,
              // 当前时间
              currentTime = new Date().getTime()
              playLoading = false

          function play() {
              if (playIndex + 1 > dataList.length - 1) {
                  playIndex = 0
              } else {
                  playIndex += 1
              }
              if (isVideo(dataList[playIndex].url)) {
                  setVideoDisplay()
              } else {
                  setImageDisplay()
                  setTimeout(function(){
                      play()
                  }, (config.interval || 5) * 1000)
              }
          }



          function playWithTime() {
              var current = getPlayTimePage()
              if (!current) {
                  showNoProgram()
              }
              // 按时间段播放，5秒校验一次时间范围
              playTimeInterval = setInterval(()=> {
                  var current = getPlayTimePage()
                  if (!current) {
                      showNoProgram()
                  }
              }, 5000)

          }

          function getPlayTimePage() {
              var currentPlayPage = null;
              playIndex = 0
              var current = dataList[playIndex]
              // 先判断当前的时间是否播放完成
              if(current.endTime && +current.endTime > currentTime) {
                  // 继续播放
                  currentPlayPage = current
                  if (isVideo(dataList[playIndex].url)) {
                      setVideoDisplay()
                  } else {
                      setImageDisplay()
                  }
                  return currentPlayPage
              }
              for(var i = playIndex + 1; i < dataList.length; i ++) {
                  // 当前页播放完成，则判断下一页是否符合播放时间
                  var nextPage = dataList[i]
                  if ((nextPage.startTime && !nextPage.endTime && +nextPage.startTime <= currentTime) || (nextPage.endTime && +nextPage.endTime >= currentTime)) {
                      playIndex = i
                      if (isVideo(dataList[playIndex].url)) {
                          setVideoDisplay()
                      } else {
                          setImageDisplay()
                      }
                      currentPlayPage = dataList[playIndex]
                      break;
                  }
              }
              return currentPlayPage
          }

          function startPlay() {
              if (dataList && dataList.length > 0) {
                  document.getElementById("no_program").style.display = 'none'
                  if (!config || !config.type || config.type == 'duration') {
                      play()
                  } else {
                      getCurrentTime()
                      playWithTime()
                  }
              } else {
                  showNoProgram()
                  setTimeout(function () {
                      startPlay()
                  }, 1000)
              }
          }

          const getCurrentTime =  () => {
              if (serverTimeInterval) {
                  clearInterval(serverTimeInterval)
                  serverTimeInterval = null;
              }
              serverTimeInterval = setInterval(() => {
                  currentTime += 1000
              }, 1000)
              return currentTime
          }

          window.onload = function () {
              playLoading = true
              resetFontSize()
              var params = getQueryParams(window.location.href)
              var templateId = params.templateId
              request(requestUrl + `/broadcast/template/${templateId}?resFlag=1`, 'GET', null, function(errors, res) {
                  if (res.code == 200 && res.data) {
                      dataList = res.data.listResource
                      config = JSON.parse(res.data.config)
                  }
                  playLoading = false
              })
              startPlay()
              window.onresize = function () {
                  resetFontSize()
              }

          }


      </script>
</head>

<body>
  <div id="app">
      <div id="no_program">节目加载中...</div>
      <img id="image" style="border: 0; width: 100%; height: 100%; display:none;"/>
      <video id="video"
             autoplay
             muted
             controls
             style="border: 0; width: 100%; height: 100%; display:none;"
      ></video>
  </div>
</body>

</html>